<!--
 * @FilePath: /web-vue/src/views/ScenerySpot/index.vue
 * @Description: 【旅游景点】管理主页
-->
<template>
  <div>
    <el-row class="data-table row-panel row-panel-first">
      <el-col>
        <el-card>
          <el-row :gutter="0">
            <!-- 【旅游景点】参数 -->
            <el-col>
              <el-form :model="queryForm" size="medium" :inline="true">
                <table
                  style="border-collapse: collapse; width: 100%"
                  class="table-common-style"
                >
                  <colgroup>
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td><div class="form-item-label">景点类型：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="sceneryType">
                          <el-select
                            v-model="queryForm.sceneryType"
                            filterable
                            clearable
                            placeholder="请选择查询参数"
                            @change="queryDataBtn()"
                          >
                            <el-option
                              v-for="item in $store.state.DICT
                                .sceneryTypeSelect"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">景点名称：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="name">
                          <el-input
                            v-model.trim="queryForm.name"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">宣传标语：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="announceTitle">
                          <el-input
                            v-model.trim="queryForm.announceTitle"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">景点状态：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="sceneryStatus">
                          <el-select
                            v-model="queryForm.sceneryStatus"
                            filterable
                            clearable
                            placeholder="请选择查询参数"
                            @change="queryDataBtn()"
                          >
                            <el-option
                              v-for="item in $store.state.DICT
                                .sceneryStatusSelect"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="10">
                        <!-- 按钮 -->
                        <el-form-item>
                          <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="queryDataBtn()"
                            :loading="requestLoading"
                            >查询
                          </el-button>
                          <el-button
                            type="success"
                            icon="el-icon-document-add"
                            @click="$refs.addForm.openAddForm(true)"
                            >新增
                          </el-button>
                          <el-button
                            type="danger"
                            icon="el-icon-delete"
                            @click="batchDelScenerySpotApi()"
                            >删除
                          </el-button>
                          <el-button
                            icon="el-icon-refresh-left"
                            @click="
                              () =>
                                Object.assign(
                                  this.queryForm,
                                  this.$options.data().queryForm
                                )
                            "
                            >清空查询条件
                          </el-button>
                        </el-form-item>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </el-form>
            </el-col>
            <!-- 【旅游景点】信息表 -->
            <el-col>
              <el-divider content-position="left">
                <h3>旅游景点信息表</h3>
              </el-divider>
              <el-table
                :data="tableData"
                row-key="id"
                max-height="400"
                border
                highlight-current-row
                v-loading="requestLoading"
                element-loading-text="正在拼命加载，请耐心等待！"
                element-loading-spinner="el-icon-loading"
                @selection-change="handleTableRowsSelect"
                @current-change="handleTableCurrentRowChange"
              >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                  fixed="left"
                  label="操作"
                  width="100%"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      icon="el-icon-edit-outline"
                      @click="$refs.editForm.openEditForm(true, scope.row)"
                      >变更
                    </el-button>
                    <el-dropdown v-if="true">
                      <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-arrow-down"
                        >更多
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>
                          <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-thumb"
                            >操作
                          </el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
                <el-table-column
                  type="index"
                  label="序号"
                  width="80"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="sceneryType"
                  label="景点类型"
                  align="center"
                >
                  <template slot-scope="scope">
                    <template
                      v-for="(item, index) in $store.state.DICT
                        .sceneryTypeSelect"
                    >
                      <el-tag
                        v-if="item.code === scope.row.sceneryType"
                        :key="index"
                        :type="item.theme"
                      >
                        {{ item.name }}
                      </el-tag>
                    </template>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="景点名称"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="sceneryImageUrl"
                  label="景点图"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="`${$store.state.API_ROOT}${scope.row.sceneryImageUrl}`"
                      :preview-src-list="[
                        `${$store.state.API_ROOT}${scope.row.sceneryImageUrl}`,
                      ]"
                    >
                    </el-image>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="announceTitle"
                  label="宣传标语"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="sceneryStatus"
                  label="景点状态"
                  align="center"
                >
                  <template slot-scope="scope">
                    <template
                      v-for="(item, index) in $store.state.DICT
                        .sceneryStatusSelect"
                    >
                      <el-tag
                        v-if="item.code === scope.row.sceneryStatus"
                        :key="index"
                        :type="item.theme"
                      >
                        {{ item.name }}
                      </el-tag>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <!-- 分页组件 -->
            <el-col>
              <el-pagination
                background
                @size-change="handlePageSizeChange"
                @current-change="handleCurrentPageChange"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                align="center"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加旅游景点表单 -->
    <AddForm ref="addForm" @afterSubmit="afterSubmitHandle()"></AddForm>
    <!-- 编辑旅游景点表单 -->
    <EditForm ref="editForm" @afterSubmit="afterSubmitHandle()"></EditForm>
  </div>
</template>

<script>
import AddForm from "./addForm";
import EditForm from "./editForm";
import {
  DateTimeRange_Picker_Option,
  DateRange_Picker_Option,
  Date_Picker_Option,
} from "@/utils/datePicker";

export default {
  name: "scenerySpotManage",
  components: {
    AddForm,
    EditForm,
  },

  data() {
    return {
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 【旅游景点】数据表
      tableData: [],
      // 【旅游景点】表已选 IDs
      tableCheckIds: [],
      // 数据加载
      requestLoading: false,
      // 查询表单参数
      queryForm: {
        id: null,
        name: null,
        sceneryType: null,
        sceneryImageUrl: null,
        announceTitle: null,
        detailArticle: null,
        sceneryStatus: null,
      },
      // 日期选择快捷方式
      DateTimeRange_Picker_Option,
      DateRange_Picker_Option,
      Date_Picker_Option,
    };
  },

  // 组件创建时
  created() {
    // 页面元素初始化
  },

  // 组件挂载时
  mounted() {
    this.queryDataBtn();
  },

  methods: {
    // 表单提交后置处理
    afterSubmitHandle() {
      this.queryScenerySpotApi();
      this.tableCheckIds = [];
    },

    // 处理表格行多选
    handleTableRowsSelect(val) {
      let ids = [];
      val.forEach((obj) => ids.push(obj.id));
      this.tableCheckIds = ids;
    },

    // 处理表格行单选
    handleTableCurrentRowChange(row, oldRow) {},

    // ---------------- 分页参数处理 START-----------------
    handleCurrentPageChange(val) {
      this.page.currentPage = val;
      // 查询【旅游景点】表
      this.queryScenerySpotApi();
    },
    handlePageSizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      // 查询【旅游景点】表
      this.queryScenerySpotApi();
    },
    // ---------------- 分页参数处理 END-----------------

    // 查询【旅游景点】
    queryDataBtn() {
      this.page.currentPage = 1;
      this.queryScenerySpotApi();
    },

    // 删除数据后：最后一页逻辑处理、表格更新
    afterDelete(deleteCount) {
      // 最后一页（旧）
      let oldLastPage = Math.ceil(this.page.total / this.page.pageSize);
      // 最后一页（新）
      let currLastPage = Math.ceil(
        (this.page.total - deleteCount) / this.page.pageSize
      );
      // 如果删除最后一页，则将当前页更新为最新的最后一页
      if (this.page.currentPage == oldLastPage) {
        this.page.currentPage = currLastPage == 0 ? 1 : currLastPage;
      }
      // 更新表格
      this.queryScenerySpotApi();
    },

    // 查询参数处理
    queryParamProcess() {
      let param = Object.assign({}, this.queryForm);
      param["pageNum"] = this.page.currentPage;
      param["pageSize"] = this.page.pageSize;

      return param;
    },

    // 查询【旅游景点】API
    queryScenerySpotApi() {
      this.requestLoading = true;

      this.$api
        .queryScenerySpot(this.queryParamProcess())
        .then((res) => {
          this.tableData = [];
          this.page.total = 0;

          let { status, message, data } = res.data;
          if (status == 200) {
            this.tableData = data.items;
            this.page.total = data.totalNum;
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "【旅游景点】信息表", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }

          this.requestLoading = false;
        })
        .catch((err) => {
          this.requestLoading = false;
          console.log(`【旅游景点】查询接口发生错误: ${err}`);
        });
    },

    // 删除【旅游景点】API
    batchDelScenerySpotApi() {
      if (this.tableCheckIds.length == 0) {
        this.$alert("请在左侧列选中要删除的数据行！", "提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: (action) => {},
        });
        return;
      }

      this.$confirm("此操作将永久删除已选中的数据, 是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          const loading = this.$loading({
            target: document.querySelector(".data-table"),
            lock: true,
            text: "正在删除，请耐心等待！",
          });

          // 发起删除请求
          this.$api
            .batchDelScenerySpot({ ids: this.tableCheckIds })
            .then((res) => {
              loading.close();

              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                // 更新【旅游景点】表
                this.afterDelete(data);
                // 提示信息
                this.$message({
                  type: "success",
                  message: `删除成功！删除记录数：${data}`,
                  duration: 1680,
                });
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$message({
                  type: "warning",
                  message: `数据没有发生更改！${message}`,
                  duration: 1680,
                });
              }
            })
            .catch((err) => {
              loading.close();
              // 查询【旅游景点】表
              this.queryScenerySpotApi();
              console.log(`【旅游景点】删除接口发生错误: ${err}`);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除。",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
